package com.yeren.service;

import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;

import com.yeren.dto.OriginalUserInfoDTO;
import com.yeren.dto.SNSUserInfoDTO;
import com.yeren.dto.WeixinUserListDTO;
import com.yeren.utils.CommonUtil;

/**
 * liubiao
 */
public class GetUserInfoService {
	/**
	 * 通过网页授权获取用户信息
	 * 
	 * @param accessToken
	 * @param openId
	 * @return SNSUserInfo
	 */
	@SuppressWarnings({ "deprecation", "unchecked" })
	public static SNSUserInfoDTO getSNSUserInfo(String accessToken,String openId){
		SNSUserInfoDTO snsUserInfo=null;
		//拼接请求地址
		String requestUrl="https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID";
		requestUrl=requestUrl.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId);
		//通过网页授权获取用户信息
		JSONObject jsonObject=CommonUtil.httpsRequest(requestUrl, "GET", null);
		if(null!=jsonObject){
			try{
				snsUserInfo=new SNSUserInfoDTO();
				//用户的标识
				snsUserInfo.setOpenId(jsonObject.getString("openid"));
				//昵称
				snsUserInfo.setNickname(jsonObject.getString("nickname"));
				//性别（1是男性，2是女性，0是未知）
				snsUserInfo.setSex(jsonObject.getInt("sex"));
				//用户所在的国家
				snsUserInfo.setCountry(jsonObject.getString("country"));
				//用户所在的省份
				snsUserInfo.setProvince(jsonObject.getString("province"));
				//用户所在的城市
				snsUserInfo.setCity(jsonObject.getString("city"));
				//用户头像
				snsUserInfo.setHeadImgUrl(jsonObject.getString("headimgurl"));
				//用户特权信息
				snsUserInfo.setPrivilegeList(JSONArray.toList(jsonObject.getJSONArray("privilege"),List.class));
				
			}catch(Exception e){
				snsUserInfo=null;
				int errorCode=jsonObject.getInt("errcode");
				String errorMsg=jsonObject.getString("errmsg");
//				log.error("获取用户信息失败errcode:{ } errmsg:{ }",errorCode,errorMsg);
			}
		}
		return snsUserInfo;
	}
	
	
	
	/**
	 * 获取用户信息
	 * 
	 * @param accessToken 接口访问凭证
	 * @param openId 用户标识
	 * @return WeixinUserInfo
	 */
	public static OriginalUserInfoDTO getUserInfo(String accessToken, String openId) {
		OriginalUserInfoDTO originalUserInfo = null;
		// 拼接请求地址
		String requestUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID";
		requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId);
		// 获取用户信息
		JSONObject jsonObject = CommonUtil.httpsRequest(requestUrl, "GET", null);

		if (null != jsonObject) {
			try {
				originalUserInfo = new OriginalUserInfoDTO();
				// 用户的标识
				originalUserInfo.setOpenId(jsonObject.getString("openid"));
				// 关注状态（1是关注，0是未关注），未关注时获取不到其余信息
				originalUserInfo.setSubscribe(jsonObject.getInt("subscribe"));
				// 用户关注时间
				originalUserInfo.setSubscribeTime(jsonObject.getString("subscribe_time"));
				// 昵称
				originalUserInfo.setNickname(jsonObject.getString("nickname"));
				// 用户的性别（1是男性，2是女性，0是未知）
				originalUserInfo.setSex(jsonObject.getInt("sex"));
				// 用户所在国家
				originalUserInfo.setCountry(jsonObject.getString("country"));
				// 用户所在省份
				originalUserInfo.setProvince(jsonObject.getString("province"));
				// 用户所在城市
				originalUserInfo.setCity(jsonObject.getString("city"));
				// 用户的语言，简体中文为zh_CN
				originalUserInfo.setLanguage(jsonObject.getString("language"));
				// 用户头像
				originalUserInfo.setHeadImgUrl(jsonObject.getString("headimgurl"));
			} catch (Exception e) {
				if (0 == originalUserInfo.getSubscribe()) {
//					log.error("用户{}已取消关注", originalUserInfo.getOpenId());
				} else {
					int errorCode = jsonObject.getInt("errcode");
					String errorMsg = jsonObject.getString("errmsg");
//					log.error("获取用户信息失败 errcode:{} errmsg:{}", errorCode, errorMsg);
				}
			}
		}
		return originalUserInfo;
	}
	
	
	/**
	 * 获取关注者列表
	 * 
	 * @param accessToken 调用接口凭证
	 * @param nextOpenId 第一个拉取的openId，不填默认从头开始拉取
	 * @return WeixinUserList
	 */
	@SuppressWarnings( { "unchecked", "deprecation" })
	public static WeixinUserListDTO getUserList(String accessToken, String nextOpenId) {
		WeixinUserListDTO weixinUserList = null;

		if (null == nextOpenId)
			nextOpenId = "";

		// 拼接请求地址
		String requestUrl = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=ACCESS_TOKEN&next_openid=NEXT_OPENID";
		requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("NEXT_OPENID", nextOpenId);
		// 获取关注者列表
		JSONObject jsonObject = CommonUtil.httpsRequest(requestUrl, "GET", null);
		// 如果请求成功
		if (null != jsonObject) {
			try {
				weixinUserList = new WeixinUserListDTO();
				weixinUserList.setTotal(jsonObject.getInt("total"));
				weixinUserList.setCount(jsonObject.getInt("count"));
				weixinUserList.setNextOpenId(jsonObject.getString("next_openid"));
				JSONObject dataObject = (JSONObject) jsonObject.get("data");
				weixinUserList.setOpenIdList(JSONArray.toList(dataObject.getJSONArray("openid"), List.class));
			} catch (JSONException e) {
				weixinUserList = null;
				int errorCode = jsonObject.getInt("errcode");
				String errorMsg = jsonObject.getString("errmsg");
//				log.error("获取关注者列表失败 errcode:{} errmsg:{}", errorCode, errorMsg);
			}
		}
		return weixinUserList;
	}
}
